import CryptoJS from 'crypto-js'

// 定义常量
const APPID = '75dc5707'
const API_SECRET = 'YWMyOGRlOGRiZDIwZDMwNTU1YjU0Yjcy'
const API_KEY = '781dde41ef975e1eb44908e0f77f877f'
const API_PATH = '/v3.5/chat'
const API_HOST = 'spark-api.xf-yun.com'

// Base64 编码函数
function base64Encode(str) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let encoded = ''
  let c1, c2, c3
  let e1, e2, e3, e4
  for (let i = 0; i < str.length; ) {
    c1 = str.charCodeAt(i++)
    c2 = str.charCodeAt(i++)
    c3 = str.charCodeAt(i++)
    e1 = c1 >> 2
    e2 = ((c1 & 3) << 4) | (c2 >> 4)
    e3 = ((c2 & 15) << 2) | (c3 >> 6)
    e4 = c3 & 63
    if (isNaN(c2)) {
      e3 = e4 = 64
    } else if (isNaN(c3)) {
      e4 = 64
    }
    encoded += chars.charAt(e1) + chars.charAt(e2) + chars.charAt(e3) + chars.charAt(e4)
  }
  return encoded
}

const getWebsocketUrl = () => {
  return new Promise((resolve) => {
    const apiKey = API_KEY
    const apiSecret = API_SECRET

    let url = `wss://${API_HOST}${API_PATH}`

    const host = API_HOST
    const date = new Date().toUTCString()
    const algorithm = 'hmac-sha256'
    const headers = 'host date request-line'
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${API_PATH} HTTP/1.1`
    const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
    const signature = CryptoJS.enc.Base64.stringify(signatureSha)
    const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
    const authorization = base64Encode(authorizationOrigin)
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
    resolve(url)
  })
}

const dialogue = (question, ttsWSRef, reply, onMessageReceived, dataRefresh, endofJudgment) => {
  getWebsocketUrl().then((url) => {
    ttsWSRef = wx.connectSocket({
      url: url,
      success() {
        console.log('WebSocket 连接已创建')
      },
      fail(error) {
        console.error('WebSocket 连接创建失败', error)
      }
    })

    // 监听 WebSocket 连接打开事件
    wx.onSocketOpen(() => {
      console.log('WebSocket 连接已打开')
      reply = ''
      if (endofJudgment) {
        endofJudgment(false)
        onMessageReceived()
      }
      const params = {
        header: {
          app_id: APPID,
          uid: 'fd3f47e4-d'
        },
        parameter: {
          chat: {
            domain: 'generalv3.5',
            temperature: 0.5,
            max_tokens: 1024
          }
        },
        payload: {
          message: {
            text: [
              {
                role: 'user',
                content: question
              }
            ]
          }
        }
      }
      wx.sendSocketMessage({
        data: JSON.stringify(params)
      })
    })

    // 监听 WebSocket 消息事件
    wx.onSocketMessage((e) => {
      const resultData = e.data
      const jsonData = JSON.parse(resultData)
      reply += jsonData.payload?.choices?.text[0]?.content || ''
      console.log(reply)
      dataRefresh(reply)

      if (jsonData.header.code !== 0) {
        console.error(`${jsonData.header.code}:${jsonData.header.message}`)
        return
      }
      if (jsonData.header.code === 0 && jsonData.header.status === 2) {
        wx.closeSocket()
      }
    })

    // 监听 WebSocket 错误事件
    wx.onSocketError(() => {
      console.error('WebSocket 发生错误')
      wx.closeSocket()
    })

    // 监听 WebSocket 关闭事件
    wx.onSocketClose(() => {
      console.log('WebSocket 连接已关闭')
      if (endofJudgment) {
        endofJudgment(true)
      }
    })
  })
}

export default dialogue
